import React, {createElement} from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Breadcrumb } from '@alifd/next';
import pathToRegexp from 'path-to-regexp';
import { asideMenuConfig } from '../../menuConfig';
import { withRouter } from 'react-router';


function urlToList(url) {
  //将隐藏目录a_b 转换为 a/b，用于后面匹配目录显示具体面包屑
  if (url.indexOf('_') > 0) {
    url = url.replace('_','/');
  }

  const urllist = url.split('/').filter(i => i);
  return urllist.map((urlItem, index) => {
    return `/${urllist.slice(0, index + 1).join('/')}`;
  });
}

function getBreadcrumb(breadcrumbNameMap, url) {
  let breadcrumb = breadcrumbNameMap[url];
  if (!breadcrumb) {
    Object.keys(breadcrumbNameMap).forEach(item => {
      if (pathToRegexp(item).test(url)) {
        breadcrumb = breadcrumbNameMap[item];
      }
    });
  }
  return breadcrumb || {};
}

@withRouter
export default class DirectoryCrumb extends React.Component {
  static contextTypes = {
    location: PropTypes.object,
    breadcrumbNameMap: PropTypes.object,
  };

  constructor(props) {
    super(props);
    this.state = {
      breadcrumb: null
    }
  }

  componentWillReceiveProps(nextProps) {
    let nextPath = nextProps.location.pathname;
    if (nextPath !== this.props.location.pathname) {
      const breadcrumb = this.conversionBreadcrumbList(nextPath);
      this.setState({
        breadcrumb,
      })
    } 

  }

  componentDidMount() {
    const breadcrumb = this.conversionBreadcrumbList();
    this.setState({
      breadcrumb,
    })
  }

  conversionBreadcrumbList = (nextPath) => {
    let routerLocation = this.props.location || this.context.location;
    let breadcrumbNameMap = this.props.breadcrumbNameMap || this.context.breadcrumbNameMap;

    if (nextPath) {
      routerLocation.pathname = nextPath;
    }

    // 根据 location 生成 面包屑
    // Generate breadcrumbs based on location
    if (routerLocation && routerLocation.pathname) {
      return this.conversionFromLocation(routerLocation, breadcrumbNameMap);
    }
  }

  conversionFromLocation = (routerLocation, breadcrumbNameMap) => {
    const { linkElement = 'a' } = this.props;
    // Convert the url to an array
    const pathSnippets = urlToList(routerLocation.pathname);
    // Loop data mosaic routing
    const extraBreadcrumbItems = pathSnippets.map((url, index) => {
      let currentBreadcrumb = {};
      //隐藏菜单匹配
      if (routerLocation.pathname.replace('_','/') === url) {
        currentBreadcrumb = getBreadcrumb(breadcrumbNameMap, routerLocation.pathname);
      } else {
        currentBreadcrumb = getBreadcrumb(breadcrumbNameMap, url);
      }
      const isLinkable = index !== pathSnippets.length - 1 && currentBreadcrumb.component;
      return currentBreadcrumb.name && !currentBreadcrumb.hideInBreadcrumb ? (
        <Breadcrumb.Item key={url}>
          {createElement(
            isLinkable ? linkElement : 'span',
            { [linkElement === 'a' ? 'href' : 'to']: url },
            currentBreadcrumb.name
          )}
        </Breadcrumb.Item>
      ) : null;
    });
    // Add home breadcrumbs to your head
    extraBreadcrumbItems.unshift(
      <Breadcrumb.Item key="home">
        {createElement(
          linkElement,
          {
            [linkElement === 'a' ? 'href' : 'to']: '/',
          },
          '首页'
        )}
      </Breadcrumb.Item>
    );
    let _extraBreadcrumbItems = extraBreadcrumbItems.filter(item => item);
    return (
      <Breadcrumb style={{marginLeft: '20px'}}>
        {_extraBreadcrumbItems}
      </Breadcrumb>
    );
  };

  render() {
    //console.log(this.props)
    // const { location } = this.props;
    // let parentPath = location.pathname.split('/')[1];
    // let paths = [];
    // if (asideMenuConfig && asideMenuConfig.length > 0) {
    //   for (let i = 0; i < asideMenuConfig.length; i++) {
    //     if (asideMenuConfig[i].path == "/" + parentPath) {
    //       paths.push({
    //         name: asideMenuConfig[i].name,
    //         path: '#' + asideMenuConfig[i].path
    //       })
    //       let _children = asideMenuConfig[i].children;
    //       if (_children) {
    //         for (let k = 0; k < _children.length; k++) {
    //           if (_children[k].path == location.pathname) {
    //             paths.push({
    //               name: _children[k].name,
    //               path: '#' + _children[k].path
    //             })
    //             break;
    //           }
    //         }
    //       }
    //       if (paths.length > 1) {
    //         paths[0].path = paths[1].path;
    //       }
    //     }
    //   }
    // }

    return (
      <div>
        {this.state.breadcrumb}
      </div>
    )
    // return (
    //   <Breadcrumb style={{marginLeft: '20px'}}>
    //       <Breadcrumb.Item link="#/dashboard/monitor">首页</Breadcrumb.Item>
    //       {
    //         paths && paths.map((ele, i) => {
    //           return (
    //             <Breadcrumb.Item key={i} link={ele.path}>{ele.name}</Breadcrumb.Item>
    //           )
    //         })
    //       }
    //   </Breadcrumb>
    // );
  }
}
